import json
import numpy as np
from pearson_score import pearson_score


# 为给定用户生成推荐内容
def generate_recommendations(dataset,user):
    if user not in dataset:
        raise TypeError('User'+user+'该用户不在数据集中')

    total_scores = {}
    similarity_sums ={}
    for u in [x for x in dataset if x!=user]:
        similarity_score = pearson_score(dataset,user,u)
        if similarity_score <=0:
            continue
        # 找出用户未曾参与评分的电影
        for item in [x for x in dataset[u] if x not in dataset[user] or
                     dataset[user][x]==0]:
            # Python 字典(Dictionary) update() 函数把字典 dict2 的键/值对更新到 dict 里
            # dict.update(dict2)
            total_scores.update({item:dataset[u][item]*similarity_score})
            similarity_sums.update({item:similarity_score})

        if len(total_scores) == 0:
            return ['No recommendations possible']

    # 创建电影评分的标准化列表
    movie_ranks = np.array([[total/similarity_sums[item],item] for item,total in total_scores.items()])
    # 根据第一列的值吧把表按降序排列
    movie_ranks = movie_ranks[np.argsort(movie_ranks[:,0])[::-1]]
    # 提取出推荐电影
    recommendations = [movie for _,movie in movie_ranks]
    return recommendations


if __name__ == '__main__':
    data_file = 'F:\python学习资料\Python-Machine-Learning-Cookbook-master\Chapter05\movie_ratings.json'
    with open(data_file,'r') as f:
        data = json.loads(f.read())
        user = 'Michael Henry'
        print("为"+user+'推荐:')
        movies = generate_recommendations(data,user)
        for i,movie in enumerate(movies):
            print(str(i+1)+'. '+movie)

        user = 'John Carson'
        print("为"+user+'推荐:')
        movies = generate_recommendations(data,user)
        for i,movie in enumerate(movies):
            print(str(i+1)+'. '+movie)

            